import type { ApiRes, ArticleDetail } from '@/type'
import { http } from '@/utils'
import { makeAutoObservable } from 'mobx'

class ArticleDetailStore {
  articleData: ArticleDetail
  constructor() {
    makeAutoObservable(this)
    this.articleData = {} as ArticleDetail
  }
  // 获取文章详情
  getDetail = async (id: string) => {
    const res = await http.get<ApiRes<ArticleDetail>>(`/articles/${id}`)
    this.articleData = res.data.data
  }
  // 关注作者
  followArt = async () => {
    // 如果当前已关注 取消关注
    // 否则就添加关注
    if (this.articleData.is_followed) {
      // 取消关注
      this.articleData.is_followed = false
      await http.delete(`/user/followings/${this.articleData.aut_id}`)
    } else {
      // 关注
      this.articleData.is_followed = true
      await http.post('/user/followings', {
        target: this.articleData.aut_id,
      })
    }
  }

  // 收藏
  collectArticle = () => {
    if (this.articleData.is_collected) {
      // 取消收藏
      this.articleData.is_collected = false
      http.delete(`/article/collections/${this.articleData.art_id}`)
    } else {
      // 收藏
      this.articleData.is_collected = true
      http.post('/article/collections', {
        target: this.articleData.art_id,
      })
    }
  }
}

export default ArticleDetailStore
